﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LucyGrid.Nodes
{
	/// <summary>
	/// Checks node status
	/// </summary>
	class Watchdog: IDisposable
	{
		public delegate void InvalidStateHandler();
		public delegate bool CheckState();
		
		
		InvalidStateHandler InvalidState;
		int CheckTimeout;
		bool Active;
		CheckState Checker;
		public Watchdog(CheckState check, InvalidStateHandler invalid, int checkTimeout)
		{
			CheckTimeout = checkTimeout;
			Checker = check;
			InvalidState = invalid;
		}

		public void Start() {
			if (Active) return;
			Active = true;
			Task.Run(() =>
			{
				Thread.CurrentThread.Name = string.Format("WATCHDOG-{0}", Thread.CurrentThread.ManagedThreadId);
				while (Active) {
					Thread.Sleep(CheckTimeout);
					if (Checker()) {
						InvalidState();
						break;
					}
				}
			});
		}
		public void Stop() {
			Active = false;
		}

		public void Dispose()
		{
			Stop();
		}
	}
}
